package net.zigin.nhi.could.waste.aop;

import net.zigin.nhi.could.waste.vo.TokenInfoBo;
import net.zigin.nhi.could.waste.exception.UnauthorizedException;
import net.zigin.nhi.could.waste.util.JWTUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

/**
 * 登录切面
 */
@Aspect
@Component
public class LoginAspect {

    private static final ThreadLocal<TokenInfoBo> t1 = new ThreadLocal<>();

    @Pointcut("@annotation(io.swagger.annotations.ApiOperation)")
    public void cutController() {
    }

    @Pointcut("@annotation(net.zigin.nhi.could.waste.annotation.LoginWhitePathAnnotation)")
    public void cutWithLogin() {
    }

    @Around("cutController() && !cutWithLogin()")
    public Object around(ProceedingJoinPoint point) throws Throwable {
        Subject subject = SecurityUtils.getSubject();
        if (!subject.isAuthenticated()) {
            throw new UnauthorizedException();
        }
        TokenInfoBo tokenInfo = JWTUtil.getTokenInfo(subject.getPrincipal().toString());
        t1.set(tokenInfo);
        Object proceed = point.proceed();
        t1.remove();
        return proceed;
    }

    public static TokenInfoBo getTokenInfo() {
        return t1.get();
    }

}
